package 网络.文件上传;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class fileUploadServer {
    public static void main(String[] args) throws IOException {
        //1.服务端在监听8888端口
        ServerSocket serverSocket = new ServerSocket(8888);
        Socket socket = serverSocket.accept();

        BufferedInputStream bufferedInputStream = new BufferedInputStream(socket.getInputStream());
        byte[] bytes = streamToByteArray(bufferedInputStream);
        String filePath = "src/main/java/网络/文件上传/jdk-8u301-linux-x64.tar.gz";
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(filePath));
        bufferedOutputStream.write(bytes);

        //向客户端回复
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bufferedWriter.write("收到图片");
        bufferedWriter.flush();//将数据刷新到数据通道
        socket.shutdownOutput();//设置写入结束标记

        bufferedWriter.close();
        bufferedOutputStream.close();
        bufferedInputStream.close();
        socket.close();
        serverSocket.close();
    }


    //将输入流转成成byte[],即将文件的内容读入到字节数组中
    public static byte[] streamToByteArray(InputStream inputStream) throws IOException {
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int len;
        while ((len = inputStream.read(b)) != -1){
            bs.write(b,0,len);
        }
        byte[] array = bs.toByteArray();
        bs.close();
        return array;
    }
}
